package com.emm.yixun.customer.service.impl.app.manage;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.AppPushService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.MessageReceiverService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.AddSubscribeReqDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.CustomerFamilyListReq;
import com.emm.yixun.common.app.servletentity.ImageListReq;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.MessageReceiverDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.IsSendEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.RelationTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.enums.SexEnum;
import com.emm.yixun.common.model.enums.SignStatusEnum;
import com.emm.yixun.common.model.enums.SubscribeBusinessStatusEnum;
import com.emm.yixun.common.utils.FileUploadPorxyUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.common.utils.SequencesGenerator;
import com.emm.yixun.customer.service.impl.app.ActivitiProcessServiceImpl;

@Service("addSubscribeManage")
public class AddSubscribeManage {

	@Autowired
	private CustomerService customerService;
	@Autowired
	private ProjectRoomService projectRoomService;
	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private FamilyMemberService familyMemberService;
	@Autowired
	private UserService userService;
	@Autowired
	private PayDepositService payDepositService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private CusAppNoticeManage cusAppNoticeManage;
	@Autowired
	private MessageReceiverService messageReceiverService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private AppPushService appPushService;
	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;
	@Autowired
	private ProjectSettingService projectSettingService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private TransactionRelationService transactionRelationService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private ImageService imageService;
	@Value("${file.serviceUrl}")
	private String fileUploadUrl;
	
	/**
	 * 检查房源是否可认购
	 * 
	 * @param reqDto 认购请求信息
	 * @param resDto 
	 * @return 
	 */
	public CommonResDTO check(AddSubscribeReqDto reqDto){
		CommonResDTO resDto = new CommonResDTO();
		try {
			String roomId = reqDto.getRoomId();
			if(StringUtils.isNotEmpty(roomId)){
				ProjectRoom room = projectRoomService.selectById(Long.parseLong(roomId));
				if(room != null){
					String roomStatus = room.getRoomStatus();
					//可售或认筹状态可认购
					if(!RoomStatusEnum.VENDIBILITY.getNo().equals(roomStatus) && !RoomStatusEnum.RESERVE.getNo().equals(roomStatus)){
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("此房源状态为:"+RoomStatusEnum.getByNo(roomStatus).getDes()+"，房源不可认购!");
						resDto.setResult("0");
					}
					//新增设置: 保留状态需判断认购客户是否就是保留客户
					//此功能放二期
				}else{
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("房源不存在");
					resDto.setResult("0");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("认筹房源错误!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增认购
	 * @param reqDto
	 * @return
	 */
	public SubscribeDto addSubscribe(AddSubscribeReqDto reqDto) {
		SubscribeDto subscribeDto = new SubscribeDto();
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			subscribeDto.setSubscribeCode(reqDto.getSubscribeCode());
			subscribeDto.setCustomerId(Long.parseLong(reqDto.getCustomerId()));
			subscribeDto.setProjectId(reqDto.getProjectId());
			subscribeDto.setProjectCode(reqDto.getProjectCode());
			subscribeDto.setRoomId(Long.parseLong(reqDto.getRoomId()));
			if(StringUtils.isNotEmpty(reqDto.getPayDepositId()) && !"null".equals(reqDto.getPayDepositId())){
				subscribeDto.setPayDepositId(Long.parseLong(reqDto.getPayDepositId()));
			}
			if(StringUtils.isNotEmpty(reqDto.getPayDepositCode())){
				subscribeDto.setPayDepositCode(reqDto.getPayDepositCode());
			}
			if(StringUtils.isNotEmpty(reqDto.getPayDepositMoney())){
				subscribeDto.setPayDepositMoney(new BigDecimal(reqDto.getPayDepositMoney()));
			}
			if(StringUtils.isNotEmpty(reqDto.getCalculateArea())){
				subscribeDto.setCalculateArea(new BigDecimal(reqDto.getCalculateArea()));
			}
			//折前单价
			if(StringUtils.isNotEmpty(reqDto.getDiscountPrice())){
				subscribeDto.setConversionPrice(new BigDecimal(reqDto.getDiscountPrice()));
			}
			//折前总价
			if(StringUtils.isNotEmpty(reqDto.getDiscountTotalPrice())){
				/*subscribeDto.setLumpsumPrice(new BigDecimal(Double.valueOf(reqDto.getDiscountTotalPrice())*10000));*/
				subscribeDto.setLumpsumPrice(new BigDecimal(Double.valueOf(reqDto.getDiscountTotalPrice())));
			}
			//折扣金额
			if(StringUtils.isNotEmpty(reqDto.getDiscountAmount())){
				subscribeDto.setDiscountAmount(new BigDecimal(reqDto.getDiscountAmount()));
			}
			//折扣比例
			if(StringUtils.isNotEmpty(reqDto.getDiscountRate())){
				subscribeDto.setDiscountRate(new BigDecimal(reqDto.getDiscountRate()));
			}
			//优惠原因
			if(StringUtils.isNotEmpty(reqDto.getPreferentialReasons())){
				subscribeDto.setPreferentialReasons(reqDto.getPreferentialReasons());
			}
			//业务状态：新增默认‘认购’状态
			subscribeDto.setBusinessStatus(SubscribeBusinessStatusEnum.SUBSCRIBE.getNo());
			//是否折扣审批
			subscribeDto.setDiscountApproval(reqDto.getDiscountApproval());
			//折扣说明
			subscribeDto.setDiscountNote(reqDto.getDiscountNote());
			//认购单价
			if(StringUtils.isNotEmpty(reqDto.getContractPrice())){
				subscribeDto.setSubscribePrice(new BigDecimal(reqDto.getContractPrice()));
			}
			//认购总价（即为认购合同金额）
			if(StringUtils.isNotEmpty(reqDto.getContractAmount())){
				/*subscribeDto.setSubscribeAmount(new BigDecimal(Double.valueOf(reqDto.getContractAmount())*10000));*/
				subscribeDto.setSubscribeAmount(new BigDecimal(Double.valueOf(reqDto.getContractAmount())));
			}
			//应收定金
			if(StringUtils.isNotEmpty(reqDto.getDepositReceivable())){
				subscribeDto.setDepositReceivable(new BigDecimal(reqDto.getDepositReceivable()));
			}
			if(StringUtils.isNotEmpty(reqDto.getDueTime())){
				subscribeDto.setDueTime(sdf.parse(reqDto.getDueTime()));
			}
			subscribeDto.setSignStatus(SignStatusEnum.UNSIGNED.getNo());
			subscribeDto.setPaymentMethod(reqDto.getPaymentMethod());
			subscribeDto.setDealCategory(reqDto.getDealCategory());
			if(StringUtils.isNotEmpty(reqDto.getSubscribeDate())){
				subscribeDto.setDidTime(sdf.parse(reqDto.getSubscribeDate()));
				subscribeDto.setSubscribeDate(sdf.parse(reqDto.getSubscribeDate()));
			}
			subscribeDto.setAuditStatus(reqDto.getAuditStatus());
			subscribeDto.setMerchantId(reqDto.getMerchantId());
			User user = userService.selectById(Long.parseLong(reqDto.getUserId()));
			subscribeDto.setUserCode(user.getUserCode());
			subscribeDto.setAccessCode(reqDto.getProjectCode());
			subscribeDto.setCreateUserId(Long.parseLong(reqDto.getUserId()));
			subscribeDto.setRemark(reqDto.getRemark());
			subscribeDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			//方案类别（0 低价；1 折扣）
			if(reqDto.getFloorType() != null && !"".equals(reqDto.getFloorType())){
				subscribeDto.setFloorType(reqDto.getFloorType());
			}
			//折后金额
			if(reqDto.getDiscountAfterAmount() != null && !"".equals(reqDto.getDiscountAfterAmount())){
				subscribeDto.setDiscountAfterPrice(new BigDecimal(reqDto.getDiscountAfterAmount()));
			}
			//推荐人信息
			if(StringUtils.isNotEmpty(reqDto.getReferenceId())){
				subscribeDto.setReferenceId(Long.valueOf(reqDto.getReferenceId()));
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceName())){
				subscribeDto.setReferenceName(reqDto.getReferenceName());
			}
			if(StringUtils.isNotEmpty(reqDto.getReferenceProportion())){
				subscribeDto.setReferenceProportion(new BigDecimal(reqDto.getReferenceProportion()));
			}
			subscribeDto.setConversionSignDate(subscribeDto.getDueTime());
			subscribeDto = subscribeService.create(subscribeDto);
			
			//dealCategoryList（成交类别列表）
			if(reqDto.getDealCategoryList() != null && reqDto.getDealCategoryList().size() >0){
				for(int d=0;d<reqDto.getDealCategoryList().size();d++){
					TransactionRelationDto tranDto = new TransactionRelationDto();
					tranDto.setMerchantId(subscribeDto.getMerchantId());
					tranDto.setProjectCode(subscribeDto.getProjectCode());
					tranDto.setProjectId(subscribeDto.getProjectId());
					tranDto.setBusinessId(subscribeDto.getId());
					tranDto.setRelationType(RelationTypeEnum.SUBSCRIBE.getNo());
					tranDto.setRelationAgentid(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
					tranDto.setProportionCommission(reqDto.getDealCategoryList().get(d).getProportionCommission());
					User userModel = userService.selectById(Long.valueOf(reqDto.getDealCategoryList().get(d).getRelationAgentId()));
					tranDto.setUserCode(userModel.getUserCode());
					tranDto.setAccessCode(subscribeDto.getAccessCode());
					tranDto.setCreateUserId(subscribeDto.getCreateUserId());
					tranDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					transactionRelationService.create(tranDto);
				}
			}
			
			//更新客户信息
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(Long.valueOf(reqDto.getCustomerId()));
			customerDto.setCustomerName(reqDto.getMemberName());
			customerDto.setPeDocumentType(reqDto.getDocumentType());
			customerDto.setPeDocumentNumber(reqDto.getDocumentNumber());
			customerDto.setCustomerPhone(reqDto.getMobile());
			customerDto.setPeContactAddress(reqDto.getMailPost());
			customerDto.setPePostcode(reqDto.getPostcode());
			customerService.update(customerDto);
			
		}catch(Exception e){
			e.printStackTrace();
			subscribeDto = null;
		}
		return subscribeDto;
	}
	
	/**
	 * 新增客户认购成员
	 * 
	 * @param subscribeDto 认购记录
	 * @param familyMemberList 认购家庭成员列表
	 * @return 
	 */
	public CommonResDTO addSubscribeFamily(SubscribeDto subscribeDto, List<CustomerFamilyListReq> cusFmReqList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			int index = 0;
			for (CustomerFamilyListReq family: cusFmReqList) {
				FamilyMemberDto fmDto = new FamilyMemberDto();
				fmDto.setCustomerId(subscribeDto.getCustomerId());
				fmDto.setProjectId(subscribeDto.getProjectId());
				fmDto.setProjectCode(subscribeDto.getProjectCode());
				fmDto.setBuyId(subscribeDto.getId());
				fmDto.setMemberName(family.getMemberName());
				fmDto.setSex(SexEnum.UNKNOW.getNo());
				fmDto.setDocumentType(family.getDocumentType());
				fmDto.setDocumentNumber(family.getDocumentNumber());
				fmDto.setMobile(family.getMobile());
				fmDto.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());
				fmDto.setMailPost(family.getMailPost());
				fmDto.setPostcode(family.getPostcode());
				if(index == 0){
					fmDto.setIsDefault("1");
				}else{
					fmDto.setIsDefault("0");
				}
				fmDto.setMerchantId(subscribeDto.getMerchantId());
				fmDto.setUserCode(subscribeDto.getUserCode());
				fmDto.setAccessCode(subscribeDto.getAccessCode());
				fmDto.setCreateUserId(subscribeDto.getCreateUserId());
				fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				fmDto.setRemark("认购家庭成员");
				familyMemberService.create(fmDto);
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增认购家庭成员失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增合同附件【图片】
	 * 
	 * @param subscribeDto 认购记录
	 * @param imageList 图片列表
	 * @return 
	 */
	public CommonResDTO addSubscribeImage(SubscribeDto subscribeDto, List<ImageListReq> imageList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			for (ImageListReq image: imageList) {
				String imgName = SequencesGenerator.getUUID("IMG")+ image.getHeadType();
				String result = FileUploadPorxyUtil.appPost(fileUploadUrl, image.getSignedUrl(), imgName);
				JSONObject resultJson = JSON.parseObject(result);
				String postResult = resultJson.getString("result");
				if (!"1".equals(postResult)) {
					resDto.setResult(ResultEnum.FAILURE.getNo());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("认购合同附件图片上传失败");
					return resDto;
				}
				String postUrl = resultJson.getString("url");
				ImageDto imageDto = new ImageDto();
				imageDto.setObjectId(subscribeDto.getId());
				imageDto.setSmallUrl(postUrl);
				imageDto.setImgType(ImgTypeEnum.SUBSCRIBE.getNo());
				imageDto.setMerchantId(subscribeDto.getMerchantId());
				imageDto.setUserCode(subscribeDto.getUserCode());
				imageDto.setAccessCode(subscribeDto.getAccessCode());
				imageDto.setRemark("认购合同附件");
				imageDto.setCreateUserId(subscribeDto.getCreateUserId());
				imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				imageService.create(imageDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增合同附件失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增客户认购推送push消息
	 * 
	 * @param subscribeDto 认购记录
	 * @return 
	 */
	public CommonResDTO addSubscribeNotice(Long id, String flag){
		CommonResDTO resDto = new CommonResDTO();
		try {
			Subscribe subscribeDto = subscribeService.selectById(id);
			//待审核数据,发送消息
			if(AuditStatusEnum.AUDIT.getNo().equals(subscribeDto.getAuditStatus())){
				//客户
				String cusName = "";
				Customer customer = customerService.selectById(subscribeDto.getCustomerId());
				if(customer != null){
					cusName = customer.getCustomerName();
				}
				
				/**
				 * 消息接收人
				 * 1、根据审批节点人员确定
				 */
				//获取当前项目下审批节点人map
				ProjectSettingDto pDto = new ProjectSettingDto();
				pDto.setProjectCode(subscribeDto.getProjectCode());
				ProjectSetting pObj = projectSettingService.selectByDto(pDto);
				Map<String, Object> variables = new HashMap<String, Object>();
				variables.put("projectApprovalUser", pObj.getProjectLeader());
				variables.put("marketingApprovalUser", pObj.getSaleLeader());
				variables.put("caseApprovalUser", pObj.getFieldLeader());
				variables.put("financeApprovalUser", pObj.getFinanceLeader());
				variables.put("saleManagerApprovalUser", pObj.getMaLeader());
				
				//获取审批人userId
				List<User> userList = new ArrayList<User>();
				ProcessInstanceHistoryLog processInstanceHistoryLog = historyService.createProcessInstanceHistoryLogQuery(subscribeDto.getProcInstId()).singleResult();
				BpmnModel model = new BpmnModel();
				if(null != processInstanceHistoryLog && null != processInstanceHistoryLog.getProcessDefinitionId()){
					model = repositoryService.getBpmnModel(processInstanceHistoryLog.getProcessDefinitionId());
					if(model != null) {
						Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();  
						for(FlowElement e : flowElements) { 
							if(e instanceof UserTask){
								List<String> userIds = activitiProcessService.getNodeUserId(subscribeDto.getMerchantId(),null,processInstanceHistoryLog.getProcessDefinitionId(),e.getId());
								for(String userId : userIds){
									User user = new User();
									user.setId(Long.valueOf(userId));
									userList.add(user);
								}
							}
						}  
					}
				}
				
				//项目
				/*String proName = "";
				Project project = null;
				if(subscribeDto.getProjectId() != null){
					project = projectService.selectById(subscribeDto.getProjectId());
					if(project != null){
						proName = project.getProjectName();
					}
				}*/
				
				//获取归属人
				UserDto userDto = new UserDto();
				userDto.setUserCode(customer.getUserCode());
				User userAgent_gsr = userService.selectByDto(userDto);
				
				/*String pushType = "SHSQ";*/
				
				//获取经纪人
				/*String userName = "";
				TransactionRelationDto transactionRelationDto = new TransactionRelationDto();
				transactionRelationDto.setBusinessId(subscribeDto.getId());
				List<TransactionRelation> transactionRelationList = transactionRelationService.selectListByDto(transactionRelationDto);
				if(transactionRelationList.size() > 0){
					for(int i=0;i< transactionRelationList.size() ;i++){
						User user = userService.selectById(transactionRelationList.get(i).getRelationAgentid());
						if(user.getUserName() != null && !"".equals(user.getUserName())){
							if(transactionRelationList.size() == 1){
								userName = user.getUserName();
							}else{
								userName += "；经纪人"+(i+1)+"："+user.getUserName();
							}
						}
					}
				}*/
				
				//认购折扣, 获取字典表dictionary_value = 'NT10' 的消息模板
				//消息模板: 认购折扣：购房折扣审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}
				if(flag == "1"){
					String msgTemp = "购房折扣审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT10");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(subscribeDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("noticeTempType", "NT10");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "认购折扣审批申请");
					noticeParamMap.put("merchantId", String.valueOf(subscribeDto.getMerchantId()));
					noticeParamMap.put("projectCode", subscribeDto.getProjectCode());
					noticeParamMap.put("userCode", subscribeDto.getUserCode());
					noticeParamMap.put("accessCode", subscribeDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(subscribeDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, customer.getCustomerName());
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "认购折扣提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
					
					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT10","认购折扣审批申请", flag);
					}
					
				//认购, 获取字典表dictionary_value = 'NT08' 的消息模板
				//消息模板: 认购：认购审批申请、房号：${roomName}；客户：${customer}；经纪人：${agent}	
				}else if(flag == "2"){
					String msgTemp = "认购审批申请。房号：${roomName}；客户：${customer}；归属人：${agent}";
					String sendMsg = "";
					DictionaryDto dicDto = new DictionaryDto();
					dicDto.setDictionaryValue("NT08");
					Dictionary dic = dictionaryService.selectByDto(dicDto);
					if(dic != null){
						msgTemp = dic.getDictionaryName();
					}
					//项目房间
					String roomContent = "";
					ProjectRoom room = projectRoomService.selectById(subscribeDto.getRoomId());
					if(room != null){
						roomContent = room.getCombinedName();
					}
					sendMsg = msgTemp.replace("${roomName}", roomContent)
							.replace("${customer}", cusName)
							.replace("${agent}", userAgent_gsr.getUserName());
//							.replace("${agent}", userName);
					//创建提醒消息及消息发送人信息
					Map<String, String> noticeParamMap = new HashMap<String, String>();
					noticeParamMap.put("noticeDicId",  dic.getId()+"");
					noticeParamMap.put("noticeTempType", "NT08");
					noticeParamMap.put("sendMsg", sendMsg);
					noticeParamMap.put("title", "认购审批申请");
					noticeParamMap.put("merchantId", String.valueOf(subscribeDto.getMerchantId()));
					noticeParamMap.put("projectCode", subscribeDto.getProjectCode());
					noticeParamMap.put("userCode", subscribeDto.getUserCode());
					noticeParamMap.put("accessCode", subscribeDto.getAccessCode());
					noticeParamMap.put("createUserId", String.valueOf(subscribeDto.getCreateUserId()));
					/*
					 * (ym) 提醒内容增加超链接 start
					 * */
					Map<String,String> replaceValuesMap=new HashMap<String,String>();
					replaceValuesMap.put(MsgUtil.ROOM_ID, String.valueOf(room.getId()));
					replaceValuesMap.put(MsgUtil.ROOM_NAME, roomContent);
					replaceValuesMap.put(MsgUtil.CUSTOMER_ID, String.valueOf(customer.getId()));
					replaceValuesMap.put(MsgUtil.CUSTOMER_NAME,cusName);
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
					replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			    	noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			    	/*
					 * (ym) 提醒内容增加超链接 end
					 * */
			    	String action = "认购提交审核提醒";
					resDto = cusAppNoticeManage.createNotice(noticeParamMap, userList, action);
					
					//推送消息
					if("1".equals(resDto.getResult())){
						//推送消息待处理......
						//pushMsg(project.getProjectCode(), proName, "NT08","认购审批申请", flag);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增认购消息失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	
	public void pushMsg(String projectCode,String projectName,String noticeTempType,String actionTitle, String flag) throws Exception{
		//1、查询认购审核申请相关推送消息
		// NT08: 认购审核申请
		List<MessageReceiverDto> msgRecList = new ArrayList<MessageReceiverDto>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
 		int year = calendar.get(Calendar.YEAR);
 		int month = calendar.get(Calendar.MONTH) + 1;
 		int day = calendar.get(Calendar.DAY_OF_MONTH);
// 		String issueTimeBefore = year + "-" + month + "-" + day + " 00:00:00"; 
 		String issueTimeAfter = year + "-" + month + "-" + day + " 23:59:59"; 
 		MessageReceiverDto withHouseMrDto = new MessageReceiverDto();
 		withHouseMrDto.setNoticeTempType(noticeTempType);
 		withHouseMrDto.setIsSend(IsSendEnum.UNSEND.getNo());
 		//loseCusMrDto.setIssueTimeBefore(sdf.parse(issueTimeBefore));
 		//推送所有小于 issueTimeAfter 时间的所有消息
 		withHouseMrDto.setIssueTimeAfter(sdf.parse(issueTimeAfter));
   	 	List<MessageReceiverDto> withHouseMrList = messageReceiverService.selectPushMsgListByDto(withHouseMrDto);
   	 	if(withHouseMrList != null){
   	 		for(MessageReceiverDto withHouseMr: withHouseMrList){
   	 			msgRecList.add(withHouseMr);
   	 		}
   	 	}
   	 	
   	 	if(msgRecList != null && msgRecList.size() > 0){
   	 		String noticeIds = "";
   	 		String msgRecIds = "";
   	 		Set<String> noticeIdSet = new HashSet<String>();
   	 		for(MessageReceiverDto msgRecDto: msgRecList){
   	 			//开始推送消息
	   	 		Map<String, String> pushMap = new HashMap<String, String>();
	   	 		if(flag == "1"){
	   	 			pushMap.put("action", "认购折扣提交审核提醒");
	   	 		}else{
	   	 			pushMap.put("action", "认购提交审核提醒");
	   	 		}
		   	 	pushMap.put("remindCategoryId", String.valueOf(msgRecDto.getDictionaryId()));
//		   	 	pushMap.put("pushType", msgRecDto.getNoticeTempType());
		   	 	pushMap.put("pushType", "SHSQ");
		   	    pushMap.put("projectCode",projectCode);
		   	    pushMap.put("projectName", projectName);
				String context = msgRecDto.getContent();
				appPushService.pushMessage(String.valueOf(msgRecDto.getReceiverId()), context,
					msgRecDto.getTitle(), pushMap);
				
				//消息ID,Set
				noticeIdSet.add(String.valueOf(msgRecDto.getNoticeId()));
				//消息接收人ID'S
				if(StringUtils.isNotEmpty(msgRecIds)){
					msgRecIds += ",";
				}
				msgRecIds += String.valueOf(msgRecDto.getId());
   	 		}
   	 		//需更新消息ID'S
   	 		if(!noticeIdSet.isEmpty()){
				for(String noticeId: noticeIdSet){
					if(StringUtils.isNotEmpty(noticeIds)){
						noticeIds += ",";
					}
					noticeIds += noticeId;
	   	 		}
   	 		}
   	 		//更新消息
   	 		NoticeDto noticeDto = new NoticeDto();
   	 		noticeDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		noticeService.updates(noticeDto, noticeIds);
   	 		//更新接收人
   	 		MessageReceiverDto updateMRDto = new MessageReceiverDto();
   	 		updateMRDto.setIsSend(IsSendEnum.SEND.getNo());
   	 		messageReceiverService.updates(updateMRDto, msgRecIds);
   	 	}
	}
	
}
